package com.zyfdroid.ambernicstartmenu.sidemenu;

import android.annotation.SuppressLint;
import android.app.AutomaticZenRule;
import android.app.NotificationManager;
import android.content.*;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.provider.Settings;
import android.service.notification.Condition;
import android.service.notification.ZenPolicy;
import android.service.voice.VoiceInteractionSession;
import android.service.voice.VoiceInteractionSessionService;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.DecelerateInterpolator;
import android.widget.*;
import com.zyfdroid.ambernicstartmenu.R;
import com.zyfdroid.ambernicstartmenu.service.KeyInjectorService;
import com.zyfdroid.ambernicstartmenu.ui.EditWalkthroughActivity;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;

public class InteractionSessionService extends VoiceInteractionSessionService {
    @Override
    public VoiceInteractionSession onNewSession(Bundle args) {
        return new InteractionSession(this);
    }

    public static class InteractionSession extends VoiceInteractionSession{

        public InteractionSession(Context context) {
            super(context);
        }

        @Override
        public void onCreate() {
            super.onCreate();
            mDestoryed = false;
        }


        @Override
        public void onShow(Bundle args, int showFlags) {
            super.onShow(args, showFlags);
            new Thread(this::loadScreenshot).start();

            View containerMenu = v.findViewById(R.id.container_menu);
            Animation animation = AnimationUtils.loadAnimation(getContext(), R.anim.slide_in_left);
            animation.setInterpolator(new DecelerateInterpolator());
            containerMenu.startAnimation(animation);
            v.findViewById(R.id.viewClose).setOnClickListener(this::close);

            doUiInitialize();
            doPageInitialize();
        }



        private boolean mDestoryed = false;
        private void loadScreenshot() {
            try{

                while (!mDestoryed){
                    if((screenshotData)!=null){

                        break;
                    }
                    Thread.sleep(100);
                }
                Bitmap bmp = BitmapFactory.decodeByteArray(screenshotData,0,screenshotData.length);
                if(bmp != null){
                    handler.post(()->{
                        if(mDestoryed){
                            return;
                        }
                        v.findViewById(R.id.tblScreenshot).setVisibility(View.VISIBLE);
                        v.findViewById(R.id.tblScreenshot).startAnimation(AnimationUtils.loadAnimation(getContext(),android.R.anim.fade_in));
                        ((ImageView) v.findViewById(R.id.imgScreenshot)).setImageBitmap(bmp);
                        v.findViewById(R.id.imgScreenshot).setOnClickListener(this::onSaveScreenshotClick);
                    });

                }
            }catch (Exception ex){

            }


        }

        View v;

        @Override
        public View onCreateContentView() {
            v = getLayoutInflater().inflate(R.layout.layout_menu,null,false);
            return v;
        }

        Handler handler = new Handler();


        private void onSaveScreenshotClick(View view) {
            view.setEnabled(false);
            view.setAlpha(0.5f);
            v.findViewById(R.id.proSaving).setVisibility(View.VISIBLE);
            canExit = false;
            new Thread(()->{
                ContentResolver resolver = getContext().getContentResolver();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
                String fileName = "Screenshot-"+sdf.format(new Date())+".png";
                ContentValues imageValues  = new ContentValues();
                imageValues .put(MediaStore.Images.Media.MIME_TYPE,"image/png");
                long date = System.currentTimeMillis() / 1000;
                imageValues .put(MediaStore.Images.Media.DATE_ADDED,date);
                imageValues .put(MediaStore.Images.Media.DATE_MODIFIED,date);
                String path = Environment.DIRECTORY_PICTURES+"/"+Environment.DIRECTORY_SCREENSHOTS;
                imageValues.put(MediaStore.Images.Media.DISPLAY_NAME,fileName);
                imageValues.put(MediaStore.Images.Media.RELATIVE_PATH,path);
                imageValues.put(MediaStore.Images.Media.IS_PENDING,1);

                Uri collection = MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);

                Uri imageUri = resolver.insert(collection,imageValues);
                if(imageUri == null){
                    Log.w("保存图片", "onSaveScreenshotClick: ");
                }
                boolean success = false;
                try(OutputStream it = resolver.openOutputStream(imageUri)){
                    it.write(screenshotData);
                    it.flush();
                    imageValues.put(MediaStore.Images.Media.IS_PENDING,0);
                    resolver.update(imageUri,imageValues,null,null);

                    Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,imageUri);
                    getContext().sendBroadcast(intent);
                    success = true;

                }catch (Exception ex){
                    ex.printStackTrace();
                }
                canExit = true;
                boolean finalSuccess = success;
                handler.post(()->{
                    if(finalSuccess){

                        view.setAlpha(1f);
                        Animation anim = AnimationUtils.loadAnimation(getContext(),android.R.anim.fade_out);
                        anim.setAnimationListener(new Animation.AnimationListener() {
                            @Override
                            public void onAnimationStart(Animation animation) {

                            }

                            @Override
                            public void onAnimationEnd(Animation animation) {

                                v.findViewById(R.id.tblScreenshot).setVisibility(View.GONE);
                                finish();

                            }

                            @Override
                            public void onAnimationRepeat(Animation animation) {

                            }
                        });
                        v.findViewById(R.id.tblScreenshot).startAnimation(anim);
                        Toast.makeText(getContext(), "保存成功", Toast.LENGTH_SHORT).show();
                    }else{
                        view.setEnabled(true);
                        view.setAlpha(1f);
                        v.findViewById(R.id.proSaving).setVisibility(View.INVISIBLE);
                        Toast.makeText(getContext(), "保存失败", Toast.LENGTH_SHORT).show();
                    }
                });
            }).start();

        }

        private byte[] screenshotData = null;
        private boolean canExit = true;
        @Override
        public void onBackPressed() {
            if(!canExit){return;}
            close(null);
        }

        @Override
        public void onDestroy() {
            super.onDestroy();
            mDestoryed = true;
            screenshotData = null;
        }

        private class VolumeChangeReceiver extends BroadcastReceiver {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (intent.getAction().equals("android.media.VOLUME_CHANGED_ACTION")) {
                    // 获取当前音量大小并设置给 SeekBar
                    int currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
                    seekBarVolume.setProgress(currentVolume);
                }
            }
        }

        boolean closing = false;
        public void close(View view) {
            if(!canExit){
                return;
            }
            if(closing){return;}
            closing = true;
            if(walkthroughLoaded){
                setWalkthroughPosition(((ListView) v.findViewById(R.id.listWalkthrough)).getFirstVisiblePosition());
            }

            Animation anim3 = AnimationUtils.loadAnimation(getContext(),android.R.anim.slide_out_right);
            anim3.setDuration(333);
            v.findViewById(R.id.tblScreenshot).startAnimation(anim3);
            View containerMenu = v.findViewById(R.id.container_menu);
            Animation animation = AnimationUtils.loadAnimation(getContext(), R.anim.slide_out_left);
            animation.setInterpolator(new AccelerateInterpolator());
            containerMenu.startAnimation(animation);
            animation.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {

                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    finish();
                }

                @Override
                public void onAnimationRepeat(Animation animation) {

                }
            });
        }
        @Override
        public void onHandleScreenshot(Bitmap screenshot) {
            new Thread(()->{
                if(screenshot != null){
                    doScreenshot(screenshot);
                }
            }).start();
        }

        @Override
        public void onHandleAssist(AssistState state) {
            super.onHandleAssist(state);
        }

        @Override
        public void onHide() {
            super.onHide();
            getContext().unregisterReceiver(volumeChangeReceiver);
            finish();
        }

        private void doScreenshot(Bitmap bmp){
            try(ByteArrayOutputStream stream = new ByteArrayOutputStream()){
                bmp.compress(Bitmap.CompressFormat.PNG,100,stream);
                screenshotData = stream.toByteArray();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        SeekBar seekBarVolume;AudioManager audioManager;
        private void doUiInitialize() {
            v.findViewById(R.id.btnOpenQuickSettings).setOnClickListener(v -> {
                KeyInjectorService.runWithService(getContext(), KeyInjectorService::showQuickSettings);
                close(v);
            });
            v.findViewById(R.id.btnSwitchRG).setOnClickListener(v->{
                KeyInjectorService.runWithService(getContext(),KeyInjectorService::doSwitchRG);
                close(v);
            });
            v.findViewById(R.id.btnPower).setOnClickListener(v->{
                KeyInjectorService.runWithService(getContext(),service -> service.doInputKeyCode("KEYCODE_POWER"));
                finish();
            });
            Switch switchAirplaneMode = v.findViewById(R.id.chkAirplaneMode);

            boolean isAirplaneModeOn = Settings.Global.getInt(getContext().getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, 0) != 0;
            switchAirplaneMode.setChecked(isAirplaneModeOn);

            switchAirplaneMode.setOnCheckedChangeListener((buttonView, isChecked) -> KeyInjectorService.runWithService(getContext(), service -> service.setAirplaneMode(isChecked)));

            seekBarVolume = v.findViewById(R.id.numVolume);
            audioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
            int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);

            seekBarVolume.setMax(maxVolume);

            int currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
            seekBarVolume.setProgress(currentVolume);
            seekBarVolume.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

                Toast previousToast = null;
                private long lastTrigger = -1;

                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                    if (fromUser) {
                        if ((audioManager.isWiredHeadsetOn() || audioManager.isBluetoothA2dpOn()) && seekBar.getProgress() > maxVolume * 0.5) {
                            seekBar.setProgress((int) (maxVolume * 0.5));
                            if(System.currentTimeMillis() - lastTrigger > 1000){
                                try{
                                    if(previousToast != null){
                                        previousToast.cancel();
                                    }
                                }catch (Exception ex){}
                                previousToast = Toast.makeText(getContext(), "请使用物理音量按键继续增大音量", Toast.LENGTH_SHORT);
                                previousToast.show();
                                lastTrigger = System.currentTimeMillis();
                            }


                            return;
                        }
                        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, progress, 0);
                    }
                }

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {
                }

                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {

                }
            });
            volumeChangeReceiver = new VolumeChangeReceiver();
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction("android.media.VOLUME_CHANGED_ACTION");
            getContext().registerReceiver(volumeChangeReceiver, intentFilter);

            SeekBar seekBarBrightness = v.findViewById(R.id.numBrightness);

// 获取系统亮度的最大值
            int maxBrightness = 255;
            seekBarBrightness.setMax(maxBrightness);
            seekBarBrightness.setMin(1);

// 获取当前亮度并设置给 SeekBar
            int currentBrightness = 0;
            try {
                currentBrightness = Settings.System.getInt(getContext().getContentResolver(), Settings.System.SCREEN_BRIGHTNESS);
            } catch (Settings.SettingNotFoundException e) {
                throw new RuntimeException(e);
            }
            seekBarBrightness.setProgress(currentBrightness);

// 设置亮度变化监听器
            seekBarBrightness.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                    // 用户通过SeekBar调整亮度时，设置系统亮度
                    if (fromUser) {
                        Settings.System.putInt(getContext().getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, progress);
//                        WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
//                        layoutParams.screenBrightness = (float) progress / maxBrightness;
//                        getWindow().setAttributes(layoutParams);
                    }
                }

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {
                    // 用户开始拖动SeekBar时，不做特殊处理
                }

                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {
                    // 用户停止拖动SeekBar时，不做特殊处理
                }
            });




        }
        private VolumeChangeReceiver volumeChangeReceiver;

        private SharedPreferences getDefault(){
            return getContext().getSharedPreferences("default",MODE_PRIVATE);
        }

        private static final int PAGE_MAIN = 0;
        private static final int PAGE_WALKTHROUGH = 1;
        private static final int PAGE_PERFORMANCE = 2;

        private int getDisplayPage(){
            return getDefault().getInt("page",PAGE_MAIN);
        }

        private void setDisplayPage(int page){
            getDefault().edit().putInt("page",page).apply();
        }

        private int getWalkthroughPosition(){
            return getDefault().getInt("wp",PAGE_MAIN);
        }

        private void setWalkthroughPosition(int page){
            getDefault().edit().putInt("wp",page).apply();
        }

        private String getWalkthrough(){
            return getDefault().getString("walkthough","尚未记载攻略。或许可以点击右上角的记载按钮记一些什么。");
        }

        private void doPageInitialize(){
            v.findViewById(R.id.pageMain).setVisibility(View.GONE);
            v.findViewById(R.id.pageWalkthrough).setVisibility(View.GONE);
            v.findViewById(R.id.pagePerformance).setVisibility(View.GONE);

            int currentPage = getDisplayPage();
            if(currentPage == PAGE_MAIN){
                v.findViewById(R.id.pageMain).setVisibility(View.VISIBLE);
            }
            if(currentPage == PAGE_WALKTHROUGH){
                v.findViewById(R.id.pageWalkthrough).setVisibility(View.VISIBLE);
                loadWalkthrough();
            }
            if(currentPage == PAGE_PERFORMANCE){
                v.findViewById(R.id.pagePerformance).setVisibility(View.VISIBLE);
            }

            v.findViewById(R.id.btnMainPage).setOnClickListener(_none -> {
                setDisplayPage(PAGE_MAIN);
                v.findViewById(R.id.pageMain).setVisibility(View.VISIBLE);
                v.findViewById(R.id.pageWalkthrough).setVisibility(View.GONE);
                v.findViewById(R.id.pagePerformance).setVisibility(View.GONE);
            });
            v.findViewById(R.id.btnWalkThroughPage).setOnClickListener(_none -> {
                setDisplayPage(PAGE_WALKTHROUGH);
                v.findViewById(R.id.pageMain).setVisibility(View.GONE);
                v.findViewById(R.id.pageWalkthrough).setVisibility(View.VISIBLE);
                v.findViewById(R.id.pagePerformance).setVisibility(View.GONE);
                if(!walkthroughLoaded){
                    loadWalkthrough();
                }
            });
            v.findViewById(R.id.btnPerformancePage).setOnClickListener(_none -> {
                setDisplayPage(PAGE_PERFORMANCE);
                v.findViewById(R.id.pageMain).setVisibility(View.GONE);
                v.findViewById(R.id.pageWalkthrough).setVisibility(View.GONE);
                v.findViewById(R.id.pagePerformance).setVisibility(View.VISIBLE);
            });
        }


        private boolean walkthroughLoaded = false;
        private void loadWalkthrough(){
            walkthroughLoaded = true;
            String[] items = ("::HEAD\n"+getWalkthrough()).split(Pattern.quote("\n"));
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(),R.layout.adapter_walkthrough_item,items){

                View.OnClickListener editWalkthoughListener = new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        close(v);
                        Intent i = new Intent(getContext(), EditWalkthroughActivity.class);
                        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        getContext().startActivity(i);
                    }
                };

                @Override
                public View getView(int position, View convertView, ViewGroup parent) {
                    if(position == 0){
                        View header = getLayoutInflater().inflate(R.layout.adapter_walkthough_header,null,false);
                        header.findViewById(R.id.btnEditWalkthrough).setOnClickListener(editWalkthoughListener);
                        return header;
                    }
                    if(convertView == null || convertView.getTag() == null){
                        convertView = getLayoutInflater().inflate(R.layout.adapter_walkthrough_item,null,false);
                        convertView.setTag(this);
                    }
                    ((TextView) convertView.findViewById(R.id.txtWalkthoughLine)).setText(getItem(position));
                    return convertView;
                }
            };
            final ListView lv = v.findViewById(R.id.listWalkthrough);
            lv.setAdapter(adapter);
            handler.postDelayed(() -> {
                lv.setSelection(getWalkthroughPosition());
            },50);

        }

    }
}
